import axios from 'axios'
import { message as ElMessage, loading as ElLoading } from '@/public/index.js'

import router from '@/router'
// 基础路径
// let condition = process.env.NODE_ENV
// console.log(condition)
let instance = axios.create({
    baseURL: process.env.VUE_APP_URL, // 在环境配置里面，需要后端配置跨域否则会报错，也可以前端vue.config.js配置下跨域
    timeout: 5000,
})
instance.defaults.headers.post['Content-Type'] = 'application/x-www-`form-urlencoded;charset=UTF-8';
instance.defaults.withCredentials = true;
// 请假接口加载 loading
let ld = null;
instance.interceptors.request.use((config) => {
    // ld?.close();
   
    let { headers } = config;
    // 在这里设置请求头
    let header = {
        'user-id': localStorage.getItem('id') || '',
        'token': localStorage.getItem('token') || ''
    }
    Object.assign(headers, header);
    // console.log('请求拦截', config)
    return config;
})

// 响应拦截
instance.interceptors.response.use((res) => {
    ld.close();
    const { data } = res
    // return res.data;
    if (!data.flag) {
        //报错信息
        ElMessage({
            type: 'error',
            text: data.message
        })
        // 登录过期或者用户不存在
        if (data.code == -1) {
            localStorage.clear();
            router.replace('/');
        }
        return Promise.reject()
    } else{
        // 存入token到本地
        res.headers['token'] && localStorage.setItem('token', res.headers['token']);
        res.headers['user-id'] && localStorage.setItem('userId', res.headers['user-id']);
        return Promise.resolve(data.data);
    }
}, (err) => {
    ld.close();
    // return err
    ElMessage({
        type: 'error',
        text: "网络错误"
    })
    return Promise.reject(err)
})
const http = {
    // get请求
    get(url, data, headers,loading) {
        if(!loading) {
            ld = ElLoading({
                text: '请求中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
       
        // 返回的是promise对象
        return instance.get(url, {
            params: data,
            headers
        })
    },

    // post请求
    post(url, data, headers,loading) {
        if(!loading) {
            ld = ElLoading({
                text: '请求中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
        // 返回的是promise对象
        return instance.post(url, data, {
            headers
        })
    },

    put(url, data = {}, headers,loading) {
        if(!loading) {
            ld = ElLoading({
                text: '请求中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
        data['_method'] = 'PUT';
        return instance.post(url, data, {
            headers
        });
    },

    delete(url, data, headers,loading) {
        if(!loading) {
            ld = ElLoading({
                text: '请求中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
        return instance.delete(url, {
            params: data,
            headers
        })
    },
}
export default http;